/**
 * 公告详情页面
 *
 * 这个页面展示了：
 * 1. 动态路由参数获取
 * 2. 公告详情展示
 * 3. 相关公告推荐
 * 4. 社交分享功能
 * 5. 面包屑导航
 */
import React, { useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useAnnouncement, useAnnouncements } from '@/hooks/useAnnouncements';
import { toast } from 'sonner';

export default function AnnouncementDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  // 获取公告详情
  const {
    data: announcement,
    isLoading,
    error,
    isError
  } = useAnnouncement(parseInt(id || '0'));

  // 获取相关公告（同分类的其他公告）
  const {
    data: relatedAnnouncementsData
  } = useAnnouncements({
    category: announcement?.category,
    size: 4,
    published_only: true
  });

  // 错误处理
  useEffect(() => {
    if (isError) {
      toast.error('公告不存在或已被删除');
      navigate('/announcements');
    }
  }, [isError, navigate]);

  // 格式化日期
  const formatDate = (dateString: string | undefined) => {
    if (!dateString) return '未知日期';

    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return '无效日期';
      }

      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (error) {
      console.error('日期格式化错误:', error);
      return '日期格式错误';
    }
  };

  // 分享功能
  const handleShare = (platform: string) => {
    const url = window.location.href;
    const title = announcement?.title || '';
    
    let shareUrl = '';
    switch (platform) {
      case 'weibo':
        shareUrl = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`;
        break;
      case 'qq':
        shareUrl = `https://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`;
        break;
      case 'wechat':
        // 微信分享需要特殊处理，这里先提示用户
        toast.info('请复制链接在微信中分享');
        navigator.clipboard.writeText(url);
        return;
      default:
        return;
    }
    
    window.open(shareUrl, '_blank', 'width=600,height=400');
  };

  // 复制链接
  const copyLink = () => {
    navigator.clipboard.writeText(window.location.href);
    toast.success('链接已复制到剪贴板');
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (!announcement) {
    return null;
  }

  // 过滤相关公告（排除当前公告）
  const relatedAnnouncements = relatedAnnouncementsData?.items?.filter(
    item => item.id !== announcement.id
  ).slice(0, 3) || [];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 面包屑导航 */}
      <div className="bg-white border-b">
        <div className="container mx-auto px-4 py-4">
          <nav className="flex items-center space-x-2 text-sm">
            <Link to="/" className="text-blue-600 hover:text-blue-800">
              首页
            </Link>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <Link to="/announcements" className="text-blue-600 hover:text-blue-800">
              公告公示
            </Link>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <span className="text-gray-600">{announcement.category}</span>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <span className="text-gray-900 truncate max-w-xs">{announcement.title}</span>
          </nav>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          {/* 公告头部 */}
          <article className="bg-white rounded-lg shadow-md overflow-hidden mb-8">
            {/* 公告标题和元信息 */}
            <div className="p-8">
              <div className="flex items-center mb-4">
                <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-orange-100 text-orange-800">
                  {announcement.category}
                </span>
              </div>

              <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-6 leading-tight">
                {announcement.title}
              </h1>

              {/* 元信息 */}
              <div className="flex flex-wrap items-center text-sm text-gray-500 mb-6 space-x-6">
                <div className="flex items-center">
                  <i className="fa-solid fa-user mr-2"></i>
                  <span>{announcement.author}</span>
                </div>
                <div className="flex items-center">
                  <i className="fa-solid fa-calendar mr-2"></i>
                  <span>{formatDate(announcement.published_at || announcement.created_at)}</span>
                </div>
                <div className="flex items-center">
                  <i className="fa-solid fa-eye mr-2"></i>
                  <span>{announcement.view_count} 次浏览</span>
                </div>
              </div>

              {/* 分享按钮 */}
              <div className="flex items-center justify-between mb-6 pb-6 border-b">
                <div className="text-sm text-gray-500">
                  分享到：
                </div>
                <div className="flex items-center space-x-3">
                  <button
                    onClick={() => handleShare('weibo')}
                    className="w-8 h-8 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors"
                    title="分享到微博"
                  >
                    <i className="fa-brands fa-weibo text-sm"></i>
                  </button>
                  <button
                    onClick={() => handleShare('qq')}
                    className="w-8 h-8 bg-blue-500 text-white rounded-full flex items-center justify-center hover:bg-blue-600 transition-colors"
                    title="分享到QQ"
                  >
                    <i className="fa-brands fa-qq text-sm"></i>
                  </button>
                  <button
                    onClick={() => handleShare('wechat')}
                    className="w-8 h-8 bg-green-500 text-white rounded-full flex items-center justify-center hover:bg-green-600 transition-colors"
                    title="分享到微信"
                  >
                    <i className="fa-brands fa-weixin text-sm"></i>
                  </button>
                  <button
                    onClick={copyLink}
                    className="w-8 h-8 bg-gray-500 text-white rounded-full flex items-center justify-center hover:bg-gray-600 transition-colors"
                    title="复制链接"
                  >
                    <i className="fa-solid fa-link text-sm"></i>
                  </button>
                </div>
              </div>

              {/* 公告摘要 */}
              {announcement.excerpt && (
                <div className="bg-orange-50 border-l-4 border-orange-400 p-4 mb-6">
                  <p className="text-orange-800 font-medium">{announcement.excerpt}</p>
                </div>
              )}
            </div>

            {/* 封面图片 */}
            {/* {announcement.cover_image && (
              <div className="px-8 mb-8">
                <img
                  src={announcement.cover_image}
                  alt={announcement.title}
                  className="w-full h-64 md:h-96 object-cover rounded-lg"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement;
                    target.style.display = 'none';
                  }}
                />
              </div>
            )} */}

            {/* 公告内容 */}
            <div className="px-8 pb-8">
              <div 
                className="prose prose-lg max-w-none prose-headings:text-gray-900 prose-p:text-gray-700 prose-a:text-blue-600 prose-strong:text-gray-900"
                dangerouslySetInnerHTML={{ __html: announcement.content }}
              />
            </div>
          </article>

          {/* 相关公告 */}
          {relatedAnnouncements.length > 0 && (
            <div className="bg-white rounded-lg shadow-md p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">相关公告</h2>
              <div className="grid gap-6">
                {relatedAnnouncements.map((item) => (
                  <div key={item.id} className="border-b border-gray-200 pb-6 last:border-b-0 last:pb-0">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center mb-2">
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                            {item.category}
                          </span>
                          <span className="text-sm text-gray-500 ml-3">
                            {formatDate(item.created_at)}
                          </span>
                        </div>
                        <h3 className="text-lg font-semibold text-gray-900 mb-2 hover:text-blue-600 transition-colors">
                          <Link to={`/announcements/${item.id}`}>
                            {item.title}
                          </Link>
                        </h3>
                        {item.excerpt && (
                          <p className="text-gray-600 text-sm line-clamp-2">
                            {item.excerpt}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              
              <div className="mt-8 text-center">
                <Link
                  to="/announcements"
                  className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors"
                >
                  查看更多公告
                  <i className="fa-solid fa-arrow-right ml-2"></i>
                </Link>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
